import os
import time
from typing import Dict, List, Optional, Any
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from ..utils.logger import logger
from ..utils.config import config
from ..utils.driver_manager import get_chrome_driver_path

class DouyinPublisher:
    def __init__(self):
        self.driver = None
        self.is_logged_in = False
        self._logger = logger  # 保存logger引用
        
        # 页面URL
        self.upload_url = "https://creator.douyin.com/creator-micro/content/upload"
        self.login_url = "https://creator.douyin.com/creator-micro/home"
        
        # 从配置中加载凭据
        self.credentials = config.get('platforms.douyin.credentials', {})

    def initialize(self) -> bool:
        """初始化浏览器驱动"""
        try:
            # 获取ChromeDriver路径
            driver_path = get_chrome_driver_path()
            if not driver_path:
                raise Exception("无法获取ChromeDriver")

            # 配置Chrome选项
            options = Options()
            if not config.get('system.debug', False):
                options.add_argument('--headless')  # 无头模式
            options.add_argument('--no-sandbox')
            options.add_argument('--disable-dev-shm-usage')
            options.add_argument('--disable-gpu')  # 禁用GPU加速
            options.add_argument('--disable-extensions')  # 禁用扩展
            options.add_argument('--disable-software-rasterizer')  # 禁用软件光栅化
            options.add_experimental_option('excludeSwitches', ['enable-logging'])  # 禁用日志
            
            # 初始化ChromeDriver
            service = Service(executable_path=driver_path)
            self.driver = webdriver.Chrome(service=service, options=options)
            
            self._logger.info("抖音发布器初始化成功")
            return True
            
        except Exception as e:
            self._logger.error(f"抖音发布器初始化失败: {str(e)}")
            return False

    def login(self) -> bool:
        """登录抖音创作者平台"""
        try:
            if not self.driver:
                if not self.initialize():
                    return False

            # 访问登录页面
            self.driver.get(self.login_url)
            
            # 等待登录二维码出现
            qr_code = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.CLASS_NAME, "login-qrcode"))
            )
            
            # 提示用户扫码
            self._logger.info("请使用抖音APP扫描二维码登录")
            
            # 等待登录成功
            WebDriverWait(self.driver, 300).until(
                EC.url_contains("creator-micro/home")
            )
            
            self.is_logged_in = True
            self._logger.info("抖音平台登录成功")
            return True
            
        except Exception as e:
            self._logger.error(f"抖音平台登录失败: {str(e)}")
            return False

    def upload_video(self, video_path: str, title: str, description: str = "",
                    tags: List[str] = None) -> bool:
        """上传视频到抖音"""
        try:
            if not os.path.exists(video_path):
                raise FileNotFoundError("视频文件不存在")

            if not self.is_logged_in:
                if not self.login():
                    return False

            # 访问上传页面
            self.driver.get(self.upload_url)
            
            # 等待上传按钮出现
            upload_input = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='file']"))
            )
            
            # 上传视频
            upload_input.send_keys(video_path)
            
            # 等待视频上传完成
            WebDriverWait(self.driver, 300).until(
                EC.presence_of_element_located((By.CLASS_NAME, "upload-success"))
            )
            
            # 填写视频信息
            title_input = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "[placeholder='请输入标题']"))
            )
            title_input.clear()
            title_input.send_keys(title)
            
            if description:
                desc_input = self.driver.find_element(By.CSS_SELECTOR, "[placeholder='添加描述']")
                desc_input.clear()
                desc_input.send_keys(description)
            
            if tags:
                for tag in tags:
                    self._add_tag(tag)
            
            # 点击发布按钮
            publish_btn = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "[data-text='发布']"))
            )
            publish_btn.click()
            
            # 等待发布完成
            WebDriverWait(self.driver, 30).until(
                EC.presence_of_element_located((By.CLASS_NAME, "publish-success"))
            )
            
            self._logger.info(f"视频上传成功: {title}")
            return True
            
        except Exception as e:
            self._logger.error(f"视频上传失败: {str(e)}")
            return False

    def _add_tag(self, tag: str):
        """添加标签"""
        try:
            # 点击添加标签按钮
            tag_btn = self.driver.find_element(By.CSS_SELECTOR, "[data-text='添加标签']")
            tag_btn.click()
            
            # 输入标签
            tag_input = WebDriverWait(self.driver, 5).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, ".tag-input"))
            )
            tag_input.send_keys(tag)
            
            # 选择第一个建议标签
            suggestion = WebDriverWait(self.driver, 5).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, ".tag-suggestion-item"))
            )
            suggestion.click()
            
        except Exception as e:
            self._logger.error(f"添加标签失败: {str(e)}")

    def close(self):
        """关闭浏览器驱动"""
        try:
            if self.driver:
                self.driver.quit()
                self.driver = None
                self.is_logged_in = False
                if self._logger:
                    self._logger.info("抖音发布器已关闭")
        except Exception as e:
            if self._logger:
                self._logger.error(f"关闭抖音发布器失败: {str(e)}")

    def __del__(self):
        """析构函数"""
        self.close()

# 创建全局抖音发布器实例
douyin_publisher = DouyinPublisher()

# 导出便捷函数
def initialize() -> bool:
    return douyin_publisher.initialize()

def login() -> bool:
    return douyin_publisher.login()

def upload_video(video_path: str, title: str, description: str = "",
                tags: List[str] = None) -> bool:
    return douyin_publisher.upload_video(video_path, title, description, tags)

def close():
    douyin_publisher.close()
